﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Home.Domain.Entities.Example;
using Home.WebUI.Areas.Example.Validation;
using Omu.ValueInjecter;
using Utilities.ViewModel;

namespace Home.WebUI.Areas.Example.Controllers
{
    public class CareerController : Controller
    {
        private ExampleDbContext db = new ExampleDbContext();
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        //
        // GET: /Example/Career/

        public ActionResult Index()
        {

            return View(db.Careers.OrderBy(n => n.Sort).ToList());
        }

        public ActionResult Create()
        {
            VCareerCreate model = new VCareerCreate();
            return View(model);
        }
        [HttpPost]
        public ActionResult Create(VCareerCreate model)
        {
            //try
            //{
                if (ModelState.IsValid)
                {
                    double? sort = db.Careers.Select(p => p.Sort).Max();
                    model.Sort = sort == null ? 1 : sort + 1;
                    Career content = new Career();
                    content.InjectFrom(model);
                    db.Careers.Add(content);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            //}
            //catch (DataException)
            //{
            //    TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            //}
            return View(model);
        }
        public ActionResult Edit(int id)
        {
            VCareerCreate model = new VCareerCreate();
            return View(model.InjectFrom(db.Careers.Find(id)));
        }
        [HttpPost]
        public ActionResult Edit(VCareerCreate model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Career content = new Career();
                    content.Id = model.Id;
                    db.Careers.Attach(content);
                    model.Map();
                    content.InjectFrom<ConvertNoNull>(model);
                    //ObjectMapperManager.DefaultInstance.GetMapper<PNews, PNews>().Map(model, content);//model的值传给content
                    db.SaveChanges();
                    TempData["Tip"] = new TipModel(1, "保存成功");
                    return RedirectToAction("Edit", new {id=model.Id });
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            return View(model);
        }

        public ActionResult MoveUp(int id)
        {
            Career content = db.Careers.Find(id);
            Career contentup = db.Careers.Where(c => c.Sort < content.Sort).OrderByDescending(c => c.Sort).FirstOrDefault();
            if (contentup == null)
            {
                return Redirect(Request.UrlReferrer.ToString());
            }
            db.Careers.Attach(content);
            content.Sort = contentup.Sort;
            db.Careers.Attach(contentup);
            contentup.Sort = contentup.Sort + 1;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    Career content = db.Careers.Find(id);
                    int newsNumer = db.UserInfos.Count(n => n.CareerId == content.Id);
                    //int newsNumer = content.News.Count();
                    if (newsNumer > 0)
                    {
                        return Content(newsNumer.ToString());
                    }
                    db.Careers.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }

        //验证是否存在此标题
        [HttpGet]
        public ActionResult TitleExists(string title,int id=0)//id为排除的值，0无排除
        {
            Func<Career, bool> where;
            if (id==0)
            {
                where= c => c.Title == title;
            }
            else
            {
                where = c => c.Title == title && c.Id != id;
            }
            bool exists = true;
            int number = db.Careers.Where(where).Count();//此处传递委托不好生成的sql语句先执行后过滤的。
            if (number==0)
            {
                exists = false;
            }
            return Json(!exists, JsonRequestBehavior.AllowGet);
        }

    }
}
